package com.sto.stoapp.db.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.db.constant.StoSiteCodeConstant;
import com.sto.stoapp.entity.BaseEntity;
import com.sto.stoapp.entity.SiteCodeEntity;
import com.sto.stoapp.http.response.download.info.NextStopInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 下一站网点资料表管理类
 * 
 * @author mgf
 * 
 */
public class NextSiteManager extends StoDataBase implements
		DownLoadDao<NextStopInfo> {

	private static NextSiteManager manager;

	private static final String SQL_QUERY_ALL = "select * from "
			+ NEXT_SITE_CODE_TABLE + " where 1=1";

	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ NEXT_SITE_CODE_TABLE + " where 1=1";

	/*
	 * @修改内容：添加按编号查找下一站网点名称
	 * 
	 * @修改人：mgf
	 */
	private static final String SQL_QUERY_NAME_BY_CODE = "select "
			+ SITE_CODE_NAME + " from " + NEXT_SITE_CODE_TABLE + " where "
			+ SITE_CODE_NUMBER + " = ? ";

	private NextSiteManager(Context context) {
		super(context);
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static NextSiteManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (manager == null) {
				manager = new NextSiteManager(context);
			}
			return manager;
		}
	}

	/**
	 * 插入单条数据
	 * 
	 * @param entity
	 * @return
	 */
	public boolean insert(NextStopInfo info) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				ContentValues values = new ContentValues();
				values.put(SITE_CODE_NUMBER, info.key);
				values.put(SITE_CODE_NAME, info.value);
				values.put(StoSiteCodeConstant.ID, info.id);
				values.put(StoSiteCodeConstant.BACKUP1, info.backup1);
				values.put(StoSiteCodeConstant.VERSION, info.version);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(NEXT_SITE_CODE_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条下一站", "成功");
				} else {
					Log.d("插入一条下一站", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 批量更新数据
	 * 
	 * @param datas
	 */
	public void insertList(List<BaseEntity> datas) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int length = datas.size();
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (int i = 0; i < length; i++) {
					long res = -1;
					SiteCodeEntity siteCodeEntity = null;
					if (datas.get(i) instanceof SiteCodeEntity) {
						siteCodeEntity = (SiteCodeEntity) datas.get(i);
					} else {
						continue;
					}
					ContentValues values = new ContentValues();
					values.put(SITE_CODE_NUMBER,
							siteCodeEntity.getSiteCodeNumber());
					values.put(SITE_CODE_NAME, siteCodeEntity.getSiteCodeName());
					res = db.insert(NEXT_SITE_CODE_TABLE, null, values);
					if (res > 0) {
						Log.d("插入一条网点全表", "成功");
					} else {
						Log.d("插入一条网点全表", "失败");
					}
				}
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	/**
	 * 查询问题件的数量
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_QUERY_COUNT, null);
			if (cursor != null && cursor.moveToFirst()) {
				count = cursor.getInt(0);
			}
			closeCursor(cursor);
			closeDb(UnifiedStaticType.READ_DATABASE);
			// System.out.println("next count = " + count);
			return count;
		}
	}

	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public List<SiteCodeEntity> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<SiteCodeEntity> data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ALL,
					null));
			return data;
		}
	}

	private List<SiteCodeEntity> getDataFromCursor(final Cursor c) {
		List<SiteCodeEntity> lstData = new ArrayList<SiteCodeEntity>();
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData.add(getSingleData(c));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

	/**
	 * 根据网点编号查询网点名称
	 * 
	 * @author mgf
	 * @return
	 */
	public String queryCodeNameByNumber(String number) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			return getSiteName(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(
					SQL_QUERY_NAME_BY_CODE, new String[] { number }));

		}
	}

	private String getSiteName(Cursor c) {
		String siteName = "";
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					siteName = c.getString(c.getColumnIndex(SITE_CODE_NAME));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return siteName;
	}

	private SiteCodeEntity getSingleData(Cursor c) {
		SiteCodeEntity data = new SiteCodeEntity();
		data.setSiteCodeNumber(c.getString(c.getColumnIndex(SITE_CODE_NUMBER)));
		data.setSiteCodeName(c.getString(c.getColumnIndex(SITE_CODE_NAME)));
		return data;
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(NEXT_SITE_CODE_TABLE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(NEXT_SITE_CODE_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(NEXT_SITE_CODE_TABLE, STATUS + "=?",
						new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public ContentValues buildContentValues(NextStopInfo entity) {
		ContentValues values = new ContentValues();
		values.put(SITE_CODE_NUMBER, entity.key);
		values.put(SITE_CODE_NAME, entity.value);
		values.put(StoSiteCodeConstant.ID, entity.id);
		values.put(StoSiteCodeConstant.BACKUP1, entity.backup1);
		values.put(StoSiteCodeConstant.VERSION, entity.version);
		values.put(STATUS, entity.status);
		return values;
	}

	/**
	 * 插入多数据
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void insertOrReplace(List<NextStopInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (NextStopInfo info : datas) {
					// long res = -1;
					ContentValues values = buildContentValues(info);
					// res = db.insert(NEXT_SITE_CODE_TABLE, null, values);
					// if (res > 0) {
					// Log.d("插入一条下一站", "成功");
					// } else {
					if (replace(values)) {
						Log.d("插入一条下一站", "成功");
					} else {
						Log.d("插入一条下一站", "失败");
					}
					// }
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(NEXT_SITE_CODE_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
}
